package day10.netserver;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HtmlServer2 {

    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10086);

        // 线程池
        ExecutorService pool = Executors.newFixedThreadPool(200);

        // 循环响应
        while (true) {
            System.out.println("有客来...");
            final Socket s = ss.accept();

            // 线程
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    try (OutputStream os = s.getOutputStream();
                            // 请求信息在inputStream里面 比如请求路径等
                            InputStream is = s.getInputStream();
                         BufferedReader br = new BufferedReader(new InputStreamReader(is))){
                        String line = br.readLine();
                        System.out.println("line:" + line);

                        String[] resource = line.split(" ");
                        String path = resource[1].substring(1);

                        File file = new File(path);

                        if (!file.exists()) {
                            String head = "HTTP/1.1 404 NOTFOUND\r\n Content-Type text/html;" +
                                    "charset=utf-8\r\n" + "\r\n\r\n";
                            os.write(head.getBytes("utf-8"));
                            os.write("the resource you want is on the mars...".getBytes());
                        } else {
                            FileInputStream fis = new FileInputStream(file);
                            String head = "HTTP/1.1 200 OK\r\n Content-Type text/html;" +
                                    "charset=utf-8\r\n" + "\r\n\r\n";
                            os.write(head.getBytes("utf-8"));
                            int len = 0;
                            byte[] b = new byte[1024];
                            while ((len = fis.read(b)) > 0) {
                                os.write(b, 0, len);
                                os.flush();
                            }
                        }
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            pool.submit(r);
        }
    }
}
